{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-11-03T07:19:46.476899Z",
     "start_time": "2025-11-03T07:19:28.490513Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "#向量数据库已经创建好了，构建链条将问题，数据库检索，大预言模型生成，规范输出\n",
    "\n",
    "# 1、创建数据库检索对象\n",
    "vectorstore=Chroma(\n",
    "    persist_directory=\"./vectorstore\",\n",
    "    embedding_function=embedding_model,\n",
    ")\n",
    "# 2、创建大模型对象\n",
    "load_dotenv()\n",
    "llm=Tongyi(model=\"qwen-turbo\",api_key=os.getenv(\"TONGYI_API_KEY\"))\n",
    "# 3、构建提示词模板\n",
    "prompt=PromptTemplate(\n",
    "    input_variables=[\"context\",\"query\",\"history\"],\n",
    "    template=\n",
    "    \"\"\"\n",
    "    你是一个专业的中文问答助手，擅长基于提供的资料回答用户问题。\n",
    "请仅根据以下背景资料回答问题，如无法找到答案，请直接回答“滚，我不懂”。\n",
    "\n",
    "背景资料：{context}\n",
    "\n",
    "历史聊天记录：{history}\n",
    "\n",
    "问题：{query}\n",
    "\n",
    "回答：\"\"\",\n",
    ")\n",
    "# 4、构建监视器，并规范向量数据库返回的内容\n",
    "retriever_tool=vectorstore.as_retriever(\n",
    "    search_type=\"similarity\",\n",
    "    search_kwargs={\"k\":5},\n",
    ")\n",
    "def format_output(outputs):\n",
    "    return \"\\n\\n\".join(output.page_content for output in outputs )\n",
    "\n",
    "# 5、添加带历史记录,规范历史记录输出格式,并限制聊天记录的条数为6\n",
    "history=[]\n",
    "def format_history(history):\n",
    "    return \"\\n\\n\".join(\n",
    "        [\n",
    "            f\"{output['role']}: {output['history_context']}\"\n",
    "            for output in history[-6:]\n",
    "        ]\n",
    "    )\n",
    "\n",
    "#6、利用大语言模型添加重述功能让模型回答更精确\n",
    "rephrase=PromptTemplate(\n",
    "    input_variables=[\"query\",\"history\"],\n",
    "    template=\"\"\"\n",
    "    请根据历史对话信息，将问题描述更加清晰。\n",
    "    历史对话：{history}\n",
    "    问题:{query}\n",
    "    \"\"\",\n",
    ")\n",
    "#rephrase_link希望收到的是一个字典，不能直接传x\n",
    "rephrase_link=(\n",
    "    {\n",
    "       \"query\": lambda x : x[\"query\"],\n",
    "       \"history\": lambda x : format_history(x[\"history\"])\n",
    "     }\n",
    "    | rephrase\n",
    "    | llm\n",
    "    | StrOutputParser()\n",
    "    |(lambda x: print(f\"===重述后的问题：===\\n{x}\\n\\n\") or x)\n",
    ")\n",
    "\n",
    "# 7、整合链条并输入问题\n",
    "chain=(\n",
    "    {\n",
    "     \"context\": lambda x : format_output(retriever_tool.invoke(\n",
    "         rephrase_link.invoke({\"query\":x.get(\"query\"),\"history\":x.get(\"history\")}),\n",
    "         k=3\n",
    "     )),\n",
    "     \"query\": lambda x : x[\"query\"],\n",
    "     \"history\": lambda x : format_history( x[\"history\"])\n",
    "     } #将输入数据原封不动地传递下去\n",
    "    | prompt\n",
    "    | llm\n",
    "    | StrOutputParser()\n",
    ")\n",
    "query=[\"不动产被占有了怎么办\",\"如果不动产已经被损坏了呢\",\"婚内强迫性行为违法吗\",\"女性强迫男性进行性行为违法吗\"]\n",
    "for i in query:\n",
    "    print(f\"====={i}=====\")\n",
    "    result=chain.invoke({\"query\":i,\"history\":history})\n",
    "    history.extend(\n",
    "        [{\"role\":\"用户\",\"history_context\": i},\n",
    "        {\"role\": \"助手\",\"history_context\":result}]\n",
    "    )\n",
    "    print(result)"
   ],
   "id": "9f552c17a4a724a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=====不动产被占有了怎么办=====\n",
      "===重述后的问题：===\n",
      "根据历史对话信息，问题“不动产被占有了怎么办”可以更加清晰地描述为：\n",
      "\n",
      "**“我的不动产（如房屋、土地等）被他人非法占有，我应该如何依法维护自己的合法权益？”**\n",
      "\n",
      "如果需要进一步明确，还可以补充以下信息：\n",
      "- 不动产的类型（如房产、宅基地、耕地等）\n",
      "- 占有人是谁（如邻居、租客、开发商等）\n",
      "- 占有时间及具体情况（是否已办理相关手续、是否有合同等）\n",
      "\n",
      "这样可以让问题更具体、便于提供针对性的法律建议。\n",
      "\n",
      "\n",
      "如果不动产被占有了，权利人可以请求返还原物及其孳息；但是，应当支付善意占有人因维护该不动产支出的必要费用。\n",
      "=====如果不动产已经被损坏了呢=====\n",
      "===重述后的问题：===\n",
      "根据历史对话内容，问题可以更清晰地表述为：\n",
      "\n",
      "**“如果不动产已经被占有人损坏了，权利人该如何维权？”**\n",
      "\n",
      "或者更正式一些的表达：\n",
      "\n",
      "**“如果不动产在被占有过程中遭到损坏，权利人可以主张哪些权利？”**\n",
      "\n",
      "这样的表述更加明确，能够帮助对方准确理解问题的核心。\n",
      "\n",
      "\n",
      "如果不动产已经被损坏了，权利人可以依法请求修理、重作、更换或者恢复原状。\n",
      "=====婚内强迫性行为违法吗=====\n",
      "===重述后的问题：===\n",
      "根据历史对话内容，问题“婚内强迫性行为违法吗”与之前讨论的“不动产被占有或损坏”的法律问题并无直接关联。为了使问题描述更加清晰，可以将其调整为：\n",
      "\n",
      "**“在婚姻关系存续期间，一方强迫另一方发生性行为是否构成违法行为？”**\n",
      "\n",
      "这样表述更明确、具体，便于针对该问题进行准确的法律分析和回答。\n",
      "\n",
      "\n",
      "婚内强迫性行为违法。根据中国法律规定，夫妻双方在婚姻关系中地位平等，一方不得对另一方实施强迫性行为。如果一方在婚姻关系中强迫另一方发生性行为，该行为可能构成犯罪，如强奸罪或强制猥亵罪，具体需结合案件情况由司法机关认定和处理。\n",
      "=====女性强迫男性进行性行为违法吗=====\n",
      "===重述后的问题：===\n",
      "根据中国法律，**女性强迫男性进行性行为同样可能构成违法**，具体是否构成犯罪需结合案件具体情况认定。\n",
      "\n",
      "依据《中华人民共和国刑法》相关规定：\n",
      "\n",
      "- **强奸罪**：以暴力、胁迫或者其他手段强奸妇女的，构成强奸罪。虽然该条款中“妇女”是特定对象，但在司法实践中，若存在对男性实施类似行为的情况，可能被认定为**强制猥亵罪**。\n",
      "  \n",
      "- **强制猥亵罪**：以暴力、胁迫或者其他方法强制猥亵他人的，构成强制猥亵罪。该罪名适用于所有性别，包括男性。\n",
      "\n",
      "因此，**无论施害者是男性还是女性，只要存在以暴力、胁迫等手段强迫他人发生性行为或进行其他性骚扰行为，均可能涉嫌犯罪**，应依法承担相应的法律责任。\n",
      "\n",
      "如遇此类情况，建议及时向公安机关报案，并保留相关证据，以便司法机关依法处理。\n",
      "\n",
      "\n",
      "女性强迫男性进行性行为可能构成犯罪，具体需结合案件情况由司法机关认定和处理。根据中国法律规定，夫妻双方在婚姻关系中地位平等，任何一方不得对另一方实施强迫性行为。如果存在强迫性行为，可能涉嫌强奸罪或强制猥亵罪等违法行为。\n"
     ]
    }
   ],
   "execution_count": 19
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
